package com.lc.pianostudent.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.lc.pianostudent.BaseApplication;
import com.lc.pianostudent.R;
import com.lc.pianostudent.conn.PostRelease;
import com.lc.pianostudent.dialog.PictureDialog;
import com.lc.pianostudent.fragment.FindFragment;
import com.lc.pianostudent.util.PictureUtil;
import com.lc.pianostudent.util.Util;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.permission.PermissionsActivity;
import com.zcx.helper.util.UtilToast;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/7/3.
 */

public class CircleImageActivity extends BasePictureActivity{
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
 //   private ArrayList<String> imagePaths = new ArrayList<>();
    private ArrayList<String> oldImagePaths = new ArrayList<>();
    private ArrayList<String> compressImagePaths = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();
    private GridView gridView;
    private GridAdapter gridAdapter;

    private EditText textView;
    private String TAG =CircleImageActivity.class.getSimpleName();
    private int width,height;
    private int degree_int = 0;
    private Bitmap bitmap;

    //发布接口
    public PostRelease postRelease = new PostRelease(new AsyCallBack<PostRelease.PostReleaseInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, PostRelease.PostReleaseInfo postReleaseInfo) throws Exception {
            UtilToast.show(toast);
            try {
                ((FindFragment.CallBack)getAppCallBack(FindFragment.class)).onRefresh();
            } catch (Exception e) {
                e.printStackTrace();
            }
            finish();
        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_image);
        setBackTrue();
        initView();
        setRightName("发布", R.color.textBlack_2e2e2e, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Log.e("=====ju",oldImagePaths.size()+"===");

                if(oldImagePaths.size() >1 &&oldImagePaths.get(oldImagePaths.size()-1).equals("paizhao")){
                    oldImagePaths.remove(oldImagePaths.size()-1);
                }
                if(oldImagePaths.size() == 1&&oldImagePaths.get(oldImagePaths.size()-1).equals("paizhao")){
                    UtilToast.show("请添加图片");
                }else {

                        for(int i = 0;i<oldImagePaths.size();i++){
                            compressImagePaths.add( PictureUtil.saveBitmap(CircleImageActivity.this, PictureUtil.compressImage(PictureUtil.getimage(oldImagePaths.get(i)))));
                            fileList.add(new File(compressImagePaths.get(i)));
                        }

                        postRelease.content = textView.getText().toString().trim();
                        postRelease.img = fileList;
                        postRelease.state = "1";
                        postRelease.type = "0";
                        postRelease.user_id = BaseApplication.BasePreferences.readUID();
                        postRelease.execute();


                }

            }
        });
    }

    private void initView(){
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;         // 屏幕宽度（像素）
        height = dm.heightPixels;       // 屏幕高度（像素）

        gridView = (GridView) findViewById(R.id.gridView);
        textView= (EditText)findViewById(R.id.et_context);
        oldImagePaths = getIntent().getStringArrayListExtra("imagePaths");
//        oldImagePaths.addAll(oldImagePaths);
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                String imgs = (String) parent.getItemAtPosition(position);
                if ("paizhao".equals(imgs) ){
                    PermissionsActivity.StartActivity(new String[]{Manifest.permission.CAMERA}, new PermissionsActivity.PermissionsCallBack() {

                        @Override
                        public void onSuccess() {

                            new PictureDialog(context){

                                @Override
                                public void onAlbum() {

                                    PhotoPickerIntent intent = new PhotoPickerIntent(CircleImageActivity.this);
                                    intent.setSelectModel(SelectModel.MULTI);
                                    intent.setShowCarema(false); // 是否显示拍照
                                    intent.setMaxTotal(6); // 最多选择照片数量，默认为6
                                    intent.setSelect(oldImagePaths.size()-1);
                                    intent.setSelectedPaths(oldImagePaths); // 已选中的照片地址， 用于回显选中状态
                                    startActivityForResult(intent, REQUEST_CAMERA_CODE);


                                }

                                @Override
                                public void onCamera() {

                                    startCamera(null);

                                }

                            }.show();

                        }

                    });

                }else{
//                    Toast.makeText(CircleImageActivity.this,"1"+position,Toast.LENGTH_SHORT).show();
                    if(oldImagePaths.size() == 6){
                        if (oldImagePaths.contains("paizhao")){
                            oldImagePaths.remove("paizhao");
                        }
                        oldImagePaths.add("paizhao");
                    }
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(CircleImageActivity.this);
//                    Log.e("----ing",oldImagePaths.size()+":imagePaths");
//                    Log.e("----ing",oldImagePaths.size()+":oldImagePaths");
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(oldImagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        oldImagePaths.add("paizhao");
        gridAdapter = new GridAdapter(oldImagePaths);
        gridView.setAdapter(gridAdapter);

    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
//                    Log.d(TAG, "数量："+list.size());
                    ArrayList<String> sasuo_list = new ArrayList<>();
                    for(int i = 0;i<list.size();i++){
                        degree_int =  Util.readPictureDegree(list.get(i));
                        bitmap = Util.toturn(PictureUtil.getimage(list.get(i)),degree_int);
                        String path_ys = PictureUtil.saveBitmap(CircleImageActivity.this, PictureUtil.compressImage(bitmap));
                        sasuo_list.add(path_ys);
                    }
                    if(list.size() != 0){
                        list.clear();
                    }

                    list.addAll(sasuo_list);

                    if (oldImagePaths.contains("paizhao")){
                        oldImagePaths.remove("paizhao");
                    }
                    oldImagePaths.add("paizhao");
                    list.addAll(oldImagePaths);

                    loadAdpater(list);


                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    oldImagePaths.clear();
                    ArrayList<String> listExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    oldImagePaths.addAll(listExtra);
//                    Log.d(TAG, "数量1："+listExtra.size());
                    loadAdpater(listExtra);
                    break;
            }
        }
    }

    @Override
    protected void resultPhotoPath(ImageView imageView, String s) {
//        String path_ys = PictureUtil.saveBitmap(CircleImageActivity.this, PictureUtil.getSmallBitmap(s));
//        String path_ys = PictureUtil.saveBitmap(CircleImageActivity.this, PictureUtil.compressImage(PictureUtil.getimage(s)));
        degree_int =  Util.readPictureDegree(s);
        bitmap = Util.toturn(PictureUtil.getimage(s),degree_int);
        String path_ys = PictureUtil.saveBitmap(CircleImageActivity.this, PictureUtil.compressImage(bitmap));
        oldImagePaths.add(path_ys);

        ArrayList<String> translate = new ArrayList<>();
        if (oldImagePaths.contains("paizhao")){
            oldImagePaths.remove("paizhao");
        }
        oldImagePaths.add("paizhao");
        translate.addAll(oldImagePaths);

        loadAdpater(translate);
    }

    private void loadAdpater(ArrayList<String> paths){
        if (oldImagePaths!=null&& oldImagePaths.size()>0){
            oldImagePaths.clear();
        }
        if (paths.contains("paizhao")){
            paths.remove("paizhao");
        }
        paths.add("paizhao");
        oldImagePaths.addAll(paths);
        gridAdapter  = new GridAdapter(oldImagePaths);
        gridView.setAdapter(gridAdapter);
        try{
            JSONArray obj = new JSONArray(oldImagePaths);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;
        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if(listUrls.size() == 7){
                listUrls.remove(listUrls.size()-1);
            }
            inflater = LayoutInflater.from(CircleImageActivity.this);
        }

        public int getCount(){
            return  listUrls.size();
        }
        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item, parent,false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                holder.image.getLayoutParams().height =  width/4;
                holder.image.getLayoutParams().width = width/4;
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }

            final String path=listUrls.get(position);
            if (path.equals("paizhao")){
                holder.image.setImageResource(R.mipmap.telephone_add);
            }else {
                Glide.with(CircleImageActivity.this)
                        .load(path)
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }
        class ViewHolder {
            ImageView image;
        }
    }

    public static void StartActivity(ArrayList<String> imagePaths) {

        BaseApplication.INSTANCE.currentActivity().startActivity(new Intent(BaseApplication.INSTANCE.currentActivity(), CircleImageActivity.class).putExtra("imagePaths", imagePaths));

    }
}
